<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Eigen: Explanation of the assertion on unaligned arrays</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
  $(document).ready(function() { init_search(); });
/* @license-end */
</script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="eigendoxy.css" rel="stylesheet" type="text/css">
<!--  -->
<script type="text/javascript" src="eigen_navtree_hacks.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="Eigen_Silly_Professor_64x64.png"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname"><a href="http://eigen.tuxfamily.org">Eigen</a>
   &#160;<span id="projectnumber">3.4.90 (git rev 67eeba6e720c5745abc77ae6c92ce0a44aa7b7ae)</span>
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.svg"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('group__TopicUnalignedArrayAssert.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">Explanation of the assertion on unaligned arrays<div class="ingroups"><a class="el" href="group__DenseMatrixManipulation__chapter.html">Dense matrix and array manipulation</a> &raquo; <a class="el" href="group__DenseMatrixManipulation__Alignement.html">Alignment issues</a></div></div>  </div>
</div><!--header-->
<div class="contents">
<p>Hello! You are seeing this webpage because your program terminated on an assertion failure like this one: </p><pre>
my_program: path/to/eigen/Eigen/src/Core/DenseStorage.h:44:
Eigen::internal::matrix_array&lt;T, Size, MatrixOptions, Align&gt;::internal::matrix_array()
[with T = double, int Size = 2, int MatrixOptions = 2, bool Align = true]:
Assertion `(reinterpret_cast&lt;size_t&gt;(array) &amp; (sizemask)) == 0 &amp;&amp; "this assertion
is explained here: <a href="http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html">http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html</a>
     READ THIS WEB PAGE !!! ****"' failed.
</pre><p>There are 4 known causes for this issue. If you can target <span class="cpp17">[c++17]</span> only with a recent compiler (e.g., GCC&gt;=7, clang&gt;=5, MSVC&gt;=19.12), then you're lucky: enabling c++17 should be enough (if not, please <a href="http://eigen.tuxfamily.org/bz/">report</a> to us). Otherwise, please read on to understand those issues and learn how to fix them.</p>
<h1><a class="anchor" id="where"></a>
Where in my own code is the cause of the problem?</h1>
<p>First of all, you need to find out where in your own code this assertion was triggered from. At first glance, the error message doesn't look helpful, as it refers to a file inside Eigen! However, since your program crashed, if you can reproduce the crash, you can get a backtrace using any debugger. For example, if you're using GCC, you can use the GDB debugger as follows: </p><div class="fragment"><div class="line">$ gdb ./my_program          # Start GDB on your program</div>
<div class="line">&gt; run                       # Start running your program</div>
<div class="line">...                         # Now reproduce the crash!</div>
<div class="line">&gt; bt                        # Obtain the backtrace</div>
</div><!-- fragment --><p> Now that you know precisely where in your own code the problem is happening, read on to understand what you need to change.</p>
<h1><a class="anchor" id="c1"></a>
Cause 1: Structures having Eigen objects as members</h1>
<p>If you have code like this,</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Foo</div>
<div class="line">{</div>
<div class="line">  <span class="comment">//...</span></div>
<div class="line">  <a class="code" href="classEigen_1_1Matrix.html">Eigen::Vector4d</a> v;</div>
<div class="line">  <span class="comment">//...</span></div>
<div class="line">};</div>
<div class="line"><span class="comment">//...</span></div>
<div class="line">Foo *foo = <span class="keyword">new</span> Foo;</div>
<div class="ttc" id="aclassEigen_1_1Matrix_html"><div class="ttname"><a href="classEigen_1_1Matrix.html">Eigen::Matrix</a></div><div class="ttdoc">The matrix class, also used for vectors and row-vectors.</div><div class="ttdef"><b>Definition:</b> Matrix.h:182</div></div>
</div><!-- fragment --><p>then you need to read this separate page: <a class="el" href="group__TopicStructHavingEigenMembers.html">Structures Having Eigen Members</a>.</p>
<p>Note that here, <a class="el" href="group__matrixtypedefs.html#ga9b2fcb53776a2829871f8a49009bef0b" title="4×1 vector of type double.">Eigen::Vector4d</a> is only used as an example, more generally the issue arises for all <a class="el" href="group__TopicFixedSizeVectorizable.html">fixed-size vectorizable Eigen types</a>.</p>
<h1><a class="anchor" id="c2"></a>
Cause 2: STL Containers or manual memory allocation</h1>
<p>If you use STL Containers such as std::vector, std::map, ..., with Eigen objects, or with classes containing Eigen objects, like this,</p>
<div class="fragment"><div class="line">std::vector&lt;Eigen::Matrix2d&gt; my_vector;</div>
<div class="line"><span class="keyword">struct </span>my_class { ... <a class="code" href="classEigen_1_1Matrix.html">Eigen::Matrix2d</a> m; ... };</div>
<div class="line">std::map&lt;int, my_class&gt; my_map;</div>
</div><!-- fragment --><p>then you need to read this separate page: <a class="el" href="group__TopicStlContainers.html">Using STL Containers with Eigen</a>.</p>
<p>Note that here, <a class="el" href="group__matrixtypedefs.html#ga3b934095f8a2834e6cc27267427239d3" title="2×2 matrix of type double.">Eigen::Matrix2d</a> is only used as an example, more generally the issue arises for all <a class="el" href="group__TopicFixedSizeVectorizable.html">fixed-size vectorizable Eigen types</a> and <a class="el" href="group__TopicStructHavingEigenMembers.html">structures having such Eigen objects as member</a>.</p>
<p>The same issue will be exhibited by any classes/functions by-passing operator new to allocate memory, that is, by performing custom memory allocation followed by calls to the placement new operator. This is for instance typically the case of <code><code>std::make_shared</code></code> or <code>std::allocate_shared</code> for which is the solution is to use an <a class="el" href="classEigen_1_1aligned__allocator.html">aligned allocator</a> as detailed in the <a class="el" href="group__TopicStlContainers.html">solution for STL containers</a>.</p>
<h1><a class="anchor" id="c3"></a>
Cause 3: Passing Eigen objects by value</h1>
<p>If some function in your code is getting an Eigen object passed by value, like this,</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> func(<a class="code" href="classEigen_1_1Matrix.html">Eigen::Vector4d</a> v);</div>
</div><!-- fragment --><p>then you need to read this separate page: <a class="el" href="group__TopicPassingByValue.html">Passing Eigen objects by value to functions</a>.</p>
<p>Note that here, <a class="el" href="group__matrixtypedefs.html#ga9b2fcb53776a2829871f8a49009bef0b" title="4×1 vector of type double.">Eigen::Vector4d</a> is only used as an example, more generally the issue arises for all <a class="el" href="group__TopicFixedSizeVectorizable.html">fixed-size vectorizable Eigen types</a>.</p>
<h1><a class="anchor" id="c4"></a>
Cause 4: Compiler making a wrong assumption on stack alignment (for instance GCC on Windows)</h1>
<p>This is a must-read for people using GCC on Windows (like MinGW or TDM-GCC). If you have this assertion failure in an innocent function declaring a local variable like this:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> foo()</div>
<div class="line">{</div>
<div class="line">  <a class="code" href="classEigen_1_1Quaternion.html">Eigen::Quaternionf</a> q;</div>
<div class="line">  <span class="comment">//...</span></div>
<div class="line">}</div>
<div class="ttc" id="aclassEigen_1_1Quaternion_html"><div class="ttname"><a href="classEigen_1_1Quaternion.html">Eigen::Quaternion</a></div><div class="ttdoc">The quaternion class used to represent 3D orientations and rotations.</div><div class="ttdef"><b>Definition:</b> Quaternion.h:276</div></div>
</div><!-- fragment --><p>then you need to read this separate page: <a class="el" href="group__TopicWrongStackAlignment.html">Compiler making a wrong assumption on stack alignment</a>.</p>
<p>Note that here, <a class="el" href="group__Geometry__Module.html#ga66aa915a26d698c60ed206818c3e4c9b">Eigen::Quaternionf</a> is only used as an example, more generally the issue arises for all <a class="el" href="group__TopicFixedSizeVectorizable.html">fixed-size vectorizable Eigen types</a>.</p>
<h1><a class="anchor" id="explanation"></a>
General explanation of this assertion</h1>
<p><a class="el" href="group__TopicFixedSizeVectorizable.html">Fixed-size vectorizable Eigen objects</a> must absolutely be created at properly aligned locations, otherwise SIMD instructions addressing them will crash. For instance, SSE/NEON/MSA/Altivec/VSX targets will require 16-byte-alignment, whereas AVX and AVX512 targets may require up to 32 and 64 byte alignment respectively.</p>
<p>Eigen normally takes care of these alignment issues for you, by setting an alignment attribute on them and by overloading their <code>operator new</code>.</p>
<p>However there are a few corner cases where these alignment settings get overridden: they are the possible causes for this assertion.</p>
<h1><a class="anchor" id="getrid"></a>
I don't care about optimal vectorization, how do I get rid of that stuff?</h1>
<p>Three possibilities: </p><ul>
<li>
Use the <code>DontAlign</code> option to <a class="el" href="classEigen_1_1Matrix.html" title="The matrix class, also used for vectors and row-vectors.">Matrix</a>, <a class="el" href="classEigen_1_1Array.html" title="General-purpose arrays with easy API for coefficient-wise operations.">Array</a>, <a class="el" href="classEigen_1_1Quaternion.html" title="The quaternion class used to represent 3D orientations and rotations.">Quaternion</a>, etc. objects that gives you trouble. This way Eigen won't try to over-align them, and thus won"t assume any special alignment. On the down side, you will pay the cost of unaligned loads/stores for them, but on modern CPUs, the overhead is either null or marginal. See <a class="el" href="group__TopicStructHavingEigenMembers.html#StructHavingEigenMembers_othersolutions">here </a> for an example. </li>
<li>
Define <a class="el" href="TopicPreprocessorDirectives.html#TopicPreprocessorDirectivesPerformance">EIGEN_MAX_STATIC_ALIGN_BYTES </a> to 0. That disables all 16-byte (and above) static alignment code, while keeping 16-byte (or above) heap alignment. This has the effect of vectorizing fixed-size objects (like Matrix4d) through unaligned stores (as controlled by <a class="el" href="TopicPreprocessorDirectives.html#TopicPreprocessorDirectivesPerformance">EIGEN_UNALIGNED_VECTORIZE </a>), while keeping unchanged the vectorization of dynamic-size objects (like MatrixXd). On 64 bytes systems, you might also define it 16 to disable only 32 and 64 bytes of over-alignment. But do note that this breaks ABI compatibility with the default behavior of static alignment. </li>
<li>
Or define both <a class="el" href="TopicPreprocessorDirectives.html#TopicPreprocessorDirectivesPerformance">EIGEN_DONT_VECTORIZE </a> and <code>EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT</code>. This keeps the 16-byte (or above) alignment code and thus preserves ABI compatibility, but completely disables vectorization. </li>
</ul>
<p>If you want to know why defining <code>EIGEN_DONT_VECTORIZE</code> does not by itself disable 16-byte (or above) alignment and the assertion, here's the explanation:</p>
<p>It doesn't disable the assertion, because otherwise code that runs fine without vectorization would suddenly crash when enabling vectorization. It doesn't disable 16-byte (or above) alignment, because that would mean that vectorized and non-vectorized code are not mutually ABI-compatible. This ABI compatibility is very important, even for people who develop only an in-house application, as for instance one may want to have in the same application a vectorized path and a non-vectorized path.</p>
<h1><a class="anchor" id="checkmycode"></a>
How can I check my code is safe regarding alignment issues?</h1>
<p>Unfortunately, there is no possibility in c++ to detect any of the aforementioned shortcoming at compile time (though static analyzers are becoming more and more powerful and could detect some of them). Even at runtime, all we can do is to catch invalid unaligned allocation and trigger the explicit assertion mentioned at the beginning of this page. Therefore, if your program runs fine on a given system with some given compilation flags, then this does not guarantee that your code is safe. For instance, on most 64 bits systems buffer are aligned on 16 bytes boundary and so, if you do not enable AVX instruction set, then your code will run fine. On the other hand, the same code may assert if moving to a more exotic platform, or enabling AVX instructions that required 32 bytes alignment by default.</p>
<p>The situation is not hopeless though. Assuming your code is well covered by unit test, then you can check its alignment safety by linking it to a custom malloc library returning 8 bytes aligned buffers only. This way all alignment shortcomings should pop-up. To this end, you must also compile your program with <a class="el" href="TopicPreprocessorDirectives.html#TopicPreprocessorDirectivesPerformance">EIGEN_MALLOC_ALREADY_ALIGNED=0 </a>. </p>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Thu Apr 21 2022 13:07:55 for Eigen by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.1 </li>
  </ul>
</div>
</body>
</html>
